package com.hdq.aspect;


import com.hdq.annotation.AutoFill;
import com.hdq.constant.AutoFillConstant;
import com.hdq.enumeration.OperationType;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.time.LocalDateTime;

@Aspect
@Component("autoFillAspect")
@Slf4j
public class AutoFillAspect {

    @Pointcut("execution(* com.hdq.mapper.*.*(..)) && @annotation(com.hdq.annotation.AutoFill)")
    public void autoFillPointcut() {}

    // 前置通知，在通知中进行公共字段的赋值
    @Before("autoFillPointcut()")
    public void autoFill(JoinPoint joinPoint) {
        log.info("运行{}", joinPoint);
        // 获取到当前被拦截的方法上的数据库操作类型git
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        AutoFill annotation = signature.getMethod().getAnnotation(AutoFill.class);
        OperationType operationType = annotation.value();

        Object[] args = joinPoint.getArgs();
        if (args.length == 0 || args == null) return;

        Object entity = args[0];
        // 准备赋值的数据

        LocalDateTime createTime = LocalDateTime.now();
        LocalDateTime updateTime = LocalDateTime.now();

        if (operationType == OperationType.INSERT) {
            try {
                Method setCreateTime = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_TIME, LocalDateTime.class);
                Method setUpdateTime = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);

                setCreateTime.invoke(entity, createTime);
                setUpdateTime.invoke(entity, updateTime);

            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }else if (operationType == OperationType.UPDATE){
            try {
                Method setUpdateTime = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
                setUpdateTime.invoke(entity, updateTime);

            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }
}
